/**
 * Created by KhoaNam on 6/25/2014.
 */

var WallSpriteObject = function(x, y, src, index, level){
    this.x = x;
    this.y = y;
    this.src = src;
    this.level = level;
    this.index = index;

}

var AnimationLayer = MyLayer.extend({
    ctor: function(nameBoundingBox, currPlayer, dice, dora){
        this._super();
        this.notInArea = nameBoundingBox;
        this.currPlayer = currPlayer;
        this.dice = dice;
        this.dora = dora;
        this.lastDoraPos =-1;

        this.botTiles = [];
        this.leftTiles = [];
        this.rightTiles = [];
        this.topTiles = [];

        this.wallLevel1 = [];
        this.wallLevel2 = [];

        this.openBot = [];
        this.openLeft = [];
        this.openRight = [];
        this.openTop = [];

        this.discardTiles = {
            1: [],
            2: [],
            3: [],
            4: []
        };

        this.tilesThrown = {
            1: this.openBot,
            2: this.openRight,
            3: this.openTop,
            4: this.openLeft
        };

        this.tilesPicked = {
            1: this.botTiles,
            2: this.rightTiles,
            3: this.topTiles,
            4: this.leftTiles
        };

        this.highlightTiles = [];
        this.position = {};
        this.isPick = false;
        this.skipButton = null;
        this.canDoTile = false;

        this.arrWallDeathObj = [];
    },

    init: function(){
        this._super();
        var size = cc.Director.getInstance().getWinSize();

        this.tilesPicked[1] = this.botTiles;
        this.tilesPicked[2] = this.rightTiles;
        this.tilesPicked[3] = this.topTiles;
        this.tilesPicked[4] = this.leftTiles;

        this.tilesThrown[1] = this.openBot;
        this.tilesThrown[2] = this.openRight;
        this.tilesThrown[3] = this.openTop;
        this.tilesThrown[4] = this.openLeft;

        this.showBotWall();
        this.showRightWall();
        this.showTopWall();
        this.showLeftWall();

        this.initPosition();

        this.skipButton = new MyButton({
            NORMAL: "res/button/skip.png",
            DOWN: "res/button/skip_pushed.png"
        });

        this.calculateStartPosition();

        this.turn = this.getPlayerPos(this.currPlayer.position);


        this.getParent().statusLayer.setTurn(this.getPlayerPos(1));


        this.autoDoTiles(0, 1);

        this.setEventResponse(this.onExtensionResponse);
    },

    loopGame: function(){
        this.isPick = true;
        this.canDoTile = true;
        this.callPickTile();
    },

    showNewDoraAndPickTileToDeadWall: function(doraPos, tile, callback){
        var src = this.wallLevel1[doraPos].src.replace(/\/.+.png/, "/" + tile + ".png");
        this.wallLevel1[doraPos].setImage(src);

        if(this.wallLevel1.length >= this.wallLevel2.length){
            tiles = this.wallLevel1;
        }
        else{
            tiles = this.wallLevel2;
        }

        var sprite = tiles.pop();
        var obj = this.arrWallDeathObj.pop();
        sprite.moveTo(INFO.GAME.TIME_THROWN_TILE, {x: obj.x, y: obj.y}, function(tatget){
            var parent = tatget._parent;
            parent.removeChild(tatget);
            var newSprite = new MyTileNoEvent(obj.src);
            newSprite.setPosition(obj.x, obj.y);
            parent.addChild(newSprite);
            if(obj.level == 1){
                this.wallLevel1[obj.index] = newSprite;
            }
            else{
                this.wallLevel2[obj.index] = newSprite;
            }
            callback(parent);
        });
    },

    onResponsePickTileFromDeathWall: function(params, callback){
        this.isPick = true;
        var tiles = [];

        var onFinished = function(target){
            cc.AudioEngine.getInstance().playEffect("res/sound/user_play.mp3");
            callback(target);
        };

        var tile;
        var obj;
        var index = 0;
        if(this.arrWallDeathObj.length == 0 || this.arrWallDeathObj[this.arrWallDeathObj.length - 1].level == 2){
            if(this.arrWallDeathObj.length > 0){
                index = this.arrWallDeathObj[this.arrWallDeathObj.length - 1].index + 1;
                tile = this.wallLevel1[index];

            }
            obj = new WallSpriteObject(tile.getPosition().x, tile.getPosition().y, tile.src, index ,  1);

        }
        else{
            index = this.arrWallDeathObj[this.arrWallDeathObj.length - 1].index + 1;
            tile = this.wallLevel2[index];
            obj = new WallSpriteObject(tile.getPosition().x, tile.getPosition().y, tile.src, index ,2);
        }
        tile.ID = params.tile;
        this.arrWallDeathObj.push(obj);

        tiles.push(tile);

        this.addTileToPlayer(params.position, tiles, params.tile);
        var that = this;
        setTimeout(function(e){
            onFinished(that);
        }, 300);
    },

    onResponsePickTile: function(params, callback){
        this.isPick = true;
        var tiles = null;

        var onFinished = function(target){
            cc.AudioEngine.getInstance().playEffect("res/sound/user_play.mp3");
            callback(target);
        };

        if(this.wallLevel1.length >= this.wallLevel2.length){
            tiles = this.wallLevel1;
        }
        else{
            tiles = this.wallLevel2;
        }
        this.addTileToPlayer(params.position, tiles, params.tile);
        var that = this;
        setTimeout(function(e){
            onFinished(that);
        }, 300);

    },

    onResponseThrowTile: function(params, callback){

        if(params.preTurn != -1){
            params.preTurn++;
            this.correctTilesThrownPosition(this.getPlayerPos(params.preTurn));
        }
        console.log("pre pos: " + params.preTurn);

        var pos = this.getPlayerPos(params.position);
        var tileID = params.tile;
        var onFinished = function(target){
            cc.AudioEngine.getInstance().playEffect("res/sound/user_play.mp3");
            callback(target);
        };

        if(pos == 1){
            for(var i = 0 ; i < this.tilesPicked[pos].length ;i++){
                if(this.tilesPicked[pos][i].ID == tileID){
                    this.addToThrownArea(this.tilesPicked[pos][i], pos, this.tilesPicked[pos][i].ID, onFinished);
                    this.tilesPicked[pos].splice(i, 1);
                    this.correctPosition(this.tilesPicked[pos], pos);
                    break;
                }
            }

        }
        else{
            this.addToThrownArea(this.tilesPicked[pos].pop(), pos , tileID, onFinished);
        }
    },

    doWinTiles: function(listTileIDs, type){
        // Get tiles
        var tmpTiles = [];
        var j = 0;

        function order (a,b) {
            return a - b;
        }

        if(type == INFO.TYPE_WIN_TILE.TSUMO || type == INFO.TYPE_WIN_TILE.RON){
            tmpTiles = listTileIDs;
        }
        else{
            listTileIDs.sort(order);
            for(var i = 0; i < this.tilesPicked[1].length ; i++){
                if(listTileIDs.length > j ){
                    if(this.tilesPicked[1][i].ID == listTileIDs[j]){
                        if(type == INFO.TYPE_WIN_TILE.CHI
                            && j == 0
                            && i < this.tilesPicked[1].length - 1
                            && this.tilesPicked[1][i+1].ID ==  listTileIDs[j]){
                            continue;
                        }
                        tmpTiles.push(this.tilesPicked[1][i]);
                        this.highlightTiles.push(this.tilesPicked[1][i]);
                        j++;
                    }
                }
                else{
                    break;
                }
            }
        }

        for(var i = 0 ; i < tmpTiles.length; i++){

            switch (type){
                case INFO.TYPE_WIN_TILE.TSUMO:
                    tmpTiles[i].showText("Tsumo");
                    break;
                case INFO.TYPE_WIN_TILE.RON:
                    tmpTiles[i].showText("Ron");
                    break;
                case INFO.TYPE_WIN_TILE.CHI:
                    tmpTiles[i].showText("Chi");
                    break;
                case INFO.TYPE_WIN_TILE.PON:
                    tmpTiles[i].showText("Pon");
                    break;
                case INFO.TYPE_WIN_TILE.OPENKAN:
                case INFO.TYPE_WIN_TILE.CLOSEKAN:
                case INFO.TYPE_WIN_TILE.LATEKAN:
                    tmpTiles[i].showText("Kan");
                    break;
            }

            tmpTiles[i].onMouseOver = function(touch, event){
                for(var j = 0 ; j < tmpTiles.length; j++){
                    //tmpTiles[j].setColor(cc.BLUE);
                    tmpTiles[j].defaultMouseOver();
                }
            };

            tmpTiles[i].onMouseOut = function(touch, event){
                for(var j = 0 ; j < tmpTiles.length; j++){
                    //tmpTiles[j].setColor(cc.WHITE);
                    tmpTiles[j].defaultMouseOut();
                }
            };

            tmpTiles[i].onTap = function(touch, event){
                var that = this.getParent();
                for(var i = 0 ; i < tmpTiles.length; i++){
                    tmpTiles[i].enableEvent = false;
                }

                var text = "";
                that.canDoTile = true;
                switch (type){
                    case INFO.TYPE_WIN_TILE.RON:
                        break;
                    case INFO.TYPE_WIN_TILE.OPENKAN:
                        text = "KAN";
                        that.callKAN(listTileIDs[0], "OPENKAN");
                        break;
                    case INFO.TYPE_WIN_TILE.CLOSEKAN:
                        text = "KAN";
                        that.callKAN(listTileIDs[0], "CLOSEKAN");
                        break;
                    case INFO.TYPE_WIN_TILE.LATEKAN:
                        text = "KAN";
                        that.callKAN(listTileIDs[0], "LATEKAN");
                        break;
                    case INFO.TYPE_WIN_TILE.PON:
                        text = "PON";
                        that.callPON(listTileIDs[0]);
                        break;
                    case INFO.TYPE_WIN_TILE.CHI:
                        text = "CHI";
                        that.callCHI(listTileIDs);
                        break;
                    case INFO.TYPE_WIN_TILE.TSUMO:
                        text = "STUMO";
                        that.callTSUMO();
                        break;
                    case INFO.TYPE_WIN_TILE.RON:
                        text = "RON";
                        that.callRON();
                        break;
                }
                that.showAlert(text);
                that.hideSkipButton();

                var that = this.getParent();
                while(that.highlightTiles.length > 0){
                    var sprite = that.highlightTiles.pop();
                    sprite.hideText();
                    sprite.onMouseOver = function(touch, event){
                        this.defaultMouseOver();
                        //this.setColor(cc.RED);
                    };

                    sprite.onMouseOut = function(touch, event){
                         this.defaultMouseOut();
                        //this.setColor(cc.WHITE);
                    };

                    sprite.onTap = function(touch, event){
                        var parent = this._parent;
                        parent.callThrowTile(this.ID);
                    };
                }
            };
        }

        this.skipButton.onTap = function(touch, event){
            console.log(" skip action");
            var that = this.getParent();
            while(that.highlightTiles.length > 0){
                var sprite = that.highlightTiles.pop();
                sprite.hideText();
                sprite.onMouseOver = function(touch, event){
                    this.defaultMouseOver();
                    //this.setColor(cc.RED);
                };

                sprite.onMouseOut = function(touch, event){
                    this.defaultMouseOut();
                    //this.setColor(cc.WHITE);
                };

                sprite.onTap = function(touch, event){
                    var parent = this._parent;
                    parent.callThrowTile(this.ID);
                };
            }
            that.canDoTile = true;

            that.callPickTile();
            that.hideSkipButton();
        }
    },

    doWinTilesResponse: function(infoObj, type){
        infoObj.winPos++;
        infoObj.losePos++;

        console.log("win " + infoObj.winPos + ", lose " + infoObj.losePos);

        var winPos = this.getPlayerPos(infoObj.winPos);
        var losePos = this.getPlayerPos(infoObj.losePos);

        function orderDesc(a, b){
            return a- b;
        }

        infoObj.winTile.sort(orderDesc);
        var tmpThrownTile = null;
        for(var i = 0 ; i < this.tilesThrown[losePos].length ; i++){
            if(infoObj.loseTile == this.tilesThrown[losePos][i].ID){
                tmpThrownTile = this.tilesThrown[losePos][i];
                this.tilesThrown[losePos].splice(i, 1);
            }
        }

        if(infoObj.winPos == this.currPlayer.position){
            var tmpTiles = [];
            var j = 0;
            for(var i = 0; i < this.tilesPicked[winPos].length ; i++){
                if(this.tilesPicked[1][i].ID == infoObj.winTile[j]){
                    if(type == INFO.TYPE_WIN_TILE.CHI
                        && j == 0
                        && i < this.tilesPicked[1].length - 1
                        && this.tilesPicked[1][i+1].ID ==  infoObj.winTile[j]){
                        continue;
                    }
                    tmpTiles.push(this.tilesPicked[winPos][i]);
                    this.tilesPicked[winPos].splice(i, 1);
                    i--;
                    j++;
                }
            }
            this.addToDiscardArea(this.discardTiles[winPos], winPos, losePos, tmpTiles, tmpThrownTile, type);

        }
        else{

            var tmpSprite = this.tilesPicked[winPos].pop();
            tmpSprite.ID = infoObj.winTile[0];
            var tmpArr = [];
            tmpArr.push(tmpSprite);
            if(type != INFO.TYPE_WIN_TILE.LATEKAN){
                tmpSprite = this.tilesPicked[winPos].pop();
                tmpSprite.ID = infoObj.winTile[1];
                tmpArr.push(tmpSprite);
                if(type == INFO.TYPE_WIN_TILE.OPENKAN){
                    tmpSprite = this.tilesPicked[winPos].pop();
                    tmpSprite.ID = infoObj.winTile[2];
                    tmpArr.push(tmpSprite);
                }
                else if(type == INFO.TYPE_WIN_TILE.CLOSEKAN){
                    tmpSprite = this.tilesPicked[winPos].pop();
                    tmpSprite.ID = infoObj.winTile[2];
                    tmpArr.push(tmpSprite);
                    tmpSprite = this.tilesPicked[winPos].pop();
                    tmpSprite.ID = infoObj.winTile[3];
                    tmpArr.push(tmpSprite);
                }
            }

            this.addToDiscardArea(this.discardTiles[winPos], winPos, losePos, tmpArr, tmpThrownTile, type);
        }
    },

    onExtensionResponse: function(event){
        var params = event.params;
        var cmd = event.cmd;
        params.position += 1;
        params.nextPosition += 1;
        params.turn += 1;
        this.getParent().statusLayer.setTurn(this.getPlayerPos(params.turn));
        if(params.turn != undefined && params.turn  == this.currPlayer.position){
            this.canDoTile = true;
        }

        if(params.CHI != undefined){
            console.log(" show CHI :" + params.CHI.winTile);
        }

        if(params.PON != undefined){
            console.log(" show PON: " + params.PON.winTile);
        }

        if(params.CLOSEKAN != undefined){
            console.log(" show KAN");
            console.log(params.CLOSEKAN);
        }

        if(params.OPENKAN != undefined){
            console.log(" show KAN");
            console.log(params.OPENKAN);
        }

        if(params.LATEKAN != undefined){
            console.log(" show KAN");
            console.log(params.LATEKAN);
        }

        if(params.RON != undefined){
            console.log(" show RON");
            console.log(params.RON);
        }

        if(params.TSUMO != undefined){
            console.log(" show TSUMO");
            console.log(params.TSUMO);
        }

        if(params.RIICHI != undefined){
            console.log(" show RIICHI: " + params.RIICHI);
        }

        console.log("AnimationPlayer extenstion response: " +  cmd);

        switch (cmd){
            case "pickTileFromDeathWall":
                this.onResponsePickTileFromDeathWall(params, function(that){
                    var isShow = false;
                    if(params.CLOSEKAN != undefined){
                        console.log(" show CLOSEKAN");
                        console.log(params.CLOSEKAN);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        that.doWinTiles(params.CLOSEKAN.winTile, INFO.TYPE_WIN_TILE.CLOSEKAN);
                        isShow = true;
                    }

                    if(params.LATEKAN != undefined){
                        console.log(" show LATEKAN");
                        console.log(params.LATEKAN);
                        that.doWinTiles(params.LATEKAN.winTile, INFO.TYPE_WIN_TILE.LATEKAN);
                        isShow = true;
                    }

                    if(isShow){
                        cc.AudioEngine.getInstance().playEffect("res/sound/chi.mp3");
                        that.showSkipButton();
                    }
                    else{

                        var count = -1;
                        for(var i = 0 ; i < that.arrWallDeathObj.length ; i++){
                            if(that.arrWallDeathObj[i].level == 1){
                                count++;
                            }
                        }

                        var currPosDora = that.lastDoraPos - count;

                        //show dora
                        for(var i = 0 ; i < params.doras.length ; i++){
                            currPosDora++;
                            var src = that.wallLevel1[currPosDora].src;
                            src = src.replace(/\/.+\.png/, "/" + params.doras[i] + ".png");
                            that.wallLevel1.setImage(src);
                        }
                    }
                });
                break;
            case "pickTile":
                this.onResponsePickTile(params, function(that){

                    var isShow = false;
                    if(params.TSUMO != null && that.currPlayer.position == params.TSUMO.winPos + 1){
                        console.log("show STUMO");
                        that.doWinTiles(that.tilesPicked[params.TSUMO.winPos + 1], INFO.TYPE_WIN_TILE.TSUMO);
                        isShow = true;
                    }

                    if(!isShow && params.CLOSEKAN != undefined){
                        console.log(" show CLOSEKAN");
                        console.log(params.CLOSEKAN);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        params.CLOSEKAN.winTile.push(params.CLOSEKAN.winTile[0]);
                        that.doWinTiles(params.CLOSEKAN.winTile, INFO.TYPE_WIN_TILE.CLOSEKAN);
                        isShow = true;
                    }

                    if(!isShow && params.LATEKAN != undefined){
                        console.log(" show LATEKAN");
                        console.log(params.LATEKAN);
                        that.doWinTiles(params.LATEKAN.winTile, INFO.TYPE_WIN_TILE.LATEKAN);
                        isShow = true;
                    }



                    if(isShow){
                        cc.AudioEngine.getInstance().playEffect("res/sound/chi.mp3");
                        that.showSkipButton();
                    }
                });
                break;
            case "throwTile":
                this.onResponseThrowTile(params, function(target){
                    var that = target.getParent();
                    if(that.currPlayer.position == params.turn){
                        var isShow = false;
                        if(params.CHI != undefined){
                            console.log(" show CHI :" + params.CHI.winTile);
                            for(var i = 0 ;i < params.CHI.winTile.length ; i++){
                                that.doWinTiles(params.CHI.winTile[i], INFO.TYPE_WIN_TILE.CHI);
                            }
                            isShow = true;
                        }

                        if(params.PON != undefined){
                            console.log(" show PON: " + params.PON.winTile);
                            params.PON.winTile.push(params.PON.winTile[0]);
                            that.doWinTiles(params.PON.winTile, INFO.TYPE_WIN_TILE.PON);
                            isShow = true;
                        }

                        if(params.OPENKAN != undefined){
                            console.log(" show KAN");
                            console.log(params.OPENKAN);
                            params.OPENKAN.winTile.push(params.OPENKAN.winTile[0]);
                            params.OPENKAN.winTile.push(params.OPENKAN.winTile[0]);
                            that.doWinTiles(params.OPENKAN.winTile, INFO.TYPE_WIN_TILE.OPENKAN);
                            isShow = true;
                        }

                        if(params.RON != undefined){
                            cc.AudioEngine.getInstance().playEffect("res/sound/chi.mp3");
                            isShow = true;
                        }
                        if(isShow){
                            cc.AudioEngine.getInstance().playEffect("res/sound/chi.mp3");
                            that.showSkipButton();
                        }
                        else{
                            target.getParent().callPickTile();
                        }

                    }
                });
                break;
            case "callChi":
                console.log("response CHI");
                this.doWinTilesResponse(params.CHI, INFO.TYPE_WIN_TILE.CHI);
                break;
            case "callPon":
                console.log("response PON");
                this.doWinTilesResponse(params.PON, INFO.TYPE_WIN_TILE.PON);
                break;
            case "callKan":
                console.log("response KAN");
                if(params.OPENKAN != undefined){
                    console.log("response OPENKAN");
                    this.doWinTilesResponse(params.OPENKAN, INFO.TYPE_WIN_TILE.OPENKAN);
                }
                else if(params.CLOSEKAN != undefined){
                    console.log("response CLOSEKAN");
                    this.doWinTilesResponse(params.CLOSEKAN, INFO.TYPE_WIN_TILE.CLOSEKAN);
                }
                else{
                    console.log("response LATEKAN");
                    this.doWinTilesResponse(params.LATEKAN, INFO.TYPE_WIN_TILE.LATEKAN);
                }

                var that = this;
                setTimeout(function(){
                    that.callPickTileFromDeathWall();
                }, 400);

                break;
            case "callTsumo":
                console.log("response TSUMO");
                console.log(params);
                this.showTiles(this.getPlayerPos(params.TSUMO.winPos), params.players[params.TSUMO.winPos], function(that){
                    for(var i = 0; i < params.TSUMO.players.length; i++){
                        if(i != params.TSUMO.winPos){
                            that.showTiles(i + 1, params.TSUMO.players[i].tiles);
                        }
                    }
                });
                break;
            case "callRon":
                console.log("response RON");
                console.log(params);
                this.showTiles(this.getPlayerPos(params.TSUMO.winPos), params.players[params.TSUMO.winPos], function(that){
                    if(params.RON.players != undefined){
                        for(var i = 0; i < params.RON.players.length; i++){
                            if(i != params.RON.winPos){
                                that.showTiles(i + 1, params.RON.players[i].tiles);
                            }
                        }
                    }
                });
                break;
            case "cancelRon":
                if(params.RON.players != undefined){
                    for(var i = 0; i < params.RON.players.length; i++){
                        if(i != params.RON.winPos){
                            that.showTiles(i + 1, params.RON.players[i].tiles);
                        }
                    }
                }
                break;

        }
    },

    showResult: function(params){

    },

    addTileToPlayer: function(pos, tiles, tileID){
        var tmpPos = this.getPlayerPos(pos);
        this.getParent().statusLayer.setTurn(tmpPos);
        switch (tmpPos){
            case 1:
                this.addToBot([tiles.pop()], tileID);
                break;
            case 2:
                this.addToRight([tiles.pop()]);
                break;
            case 3:
                this.addToTop([tiles.pop()]);
                break;
            case 4:
                this.addToLeft([tiles.pop()]);
                break;
        }
    },

    autoDoTiles: function(count,pos){
        if(count < 3){
            switch (pos){
                case 1:
                    this.addToBot([this.wallLevel2.pop(),this.wallLevel2.pop(), this.wallLevel1.pop(), this.wallLevel1.pop()]);
                    break;
                case 2:
                    this.addToRight([this.wallLevel2.pop(),this.wallLevel2.pop(), this.wallLevel1.pop(), this.wallLevel1.pop()]);
                    break;
                case 3:
                    this.addToTop([this.wallLevel2.pop(),this.wallLevel2.pop(), this.wallLevel1.pop(), this.wallLevel1.pop()]);
                    break;
                case 4:
                    this.addToLeft([this.wallLevel2.pop(),this.wallLevel2.pop(), this.wallLevel1.pop(), this.wallLevel1.pop()]);
                    break;
            }
        }
        else{
            switch (pos){
                case 1:
                    this.addToBot([this.wallLevel1.pop()]);
                    break;
                case 2:
                    this.addToRight([this.wallLevel2.pop()]);
                    break;
                case 3:
                    this.addToTop([this.wallLevel1.pop()]);
                    break;
                case 4:
                    this.addToLeft([this.wallLevel2.pop()]);
                    break;
            }
        }

        var that = this;

        setTimeout(function(){
            cc.AudioEngine.getInstance().playEffect("res/sound/user_play.mp3");
        }, 300);

        setTimeout(function(e){

            if(pos == 4){
                count+=1;
                pos = 0;
            }
            if(count < 4){
                that.autoDoTiles(count, pos + 1);
            }
            else{
                that.sortTilesAnimation();
            }
        }, 500);
    },

    showBotWall: function(){
        var size = cc.Director.getInstance().getWinSize();
        // Show bot wall
        var widthWall = (INFO.TILE.WALL_BOT_WIDTH + INFO.TILE.DISTANCE)* 17 + INFO.TILE.DISTANCE_OTHER_WALL + INFO.TILE.WALL_LEFT_WIDTH;

        // get start pos of bot wall
        var y = size.height/2 - this.notInArea.height/2 - 3*INFO.TILE.WALL_BOT_HEIGHT + 2*INFO.TILE.OVERPLAY - INFO.TILE.DISTANCE_OTHER_AREA;
        var x = size.width/2 - widthWall/2 + INFO.TILE.DISTANCE_OTHER_WALL + INFO.TILE.WALL_LEFT_WIDTH;

        y -= INFO.TILE.WALL_BOT_HEIGHT/2;
        x += INFO.TILE.WALL_BOT_WIDTH/2;

        x = parseInt(x, 10);
        y = parseInt(y, 10);

        for(var i = 0 ; i < 17 ;i++){
            var sprite = new MyTileNoEvent("res/up_0/34.png");
            sprite.setPosition(x + i*(INFO.TILE.DISTANCE + INFO.TILE.WALL_BOT_WIDTH), y);
            this.addChild(sprite,50);
            this.wallLevel2.push(sprite);
        }

        for(var i = 0 ; i < 17 ;i++){
            var sprite = new MyTileNoEvent("res/up_0/34.png");
            sprite.setPosition(x + i*(INFO.TILE.DISTANCE + INFO.TILE.WALL_BOT_WIDTH), y  + 15);
            this.addChild(sprite, 51);
            this.wallLevel1.push(sprite);
        }
    },

    showTopWall: function(){
        var size = cc.Director.getInstance().getWinSize();
        // Show bot wall
        var widthWall = (INFO.TILE.WALL_BOT_WIDTH + INFO.TILE.DISTANCE)* 17 + INFO.TILE.DISTANCE_OTHER_WALL + INFO.TILE.WALL_LEFT_WIDTH;

        // get start pos of bot wall
        var y = size.height/2 + this.notInArea.height/2 + 3*INFO.TILE.WALL_BOT_HEIGHT - 2*INFO.TILE.OVERPLAY + INFO.TILE.DISTANCE_OTHER_AREA;
        var x = size.width/2 + widthWall/2 - INFO.TILE.DISTANCE_OTHER_WALL - INFO.TILE.WALL_LEFT_WIDTH;

        y += INFO.TILE.WALL_BOT_HEIGHT/2;
        x -= INFO.TILE.WALL_BOT_WIDTH/2;

        x = parseInt(x, 10);
        y = parseInt(y, 10);

        for(var i = 0 ; i < 17 ; i++){
            var sprite = new MyTileNoEvent("res/up_0/34.png");
            sprite.setPosition(x - i*(INFO.TILE.DISTANCE + INFO.TILE.WALL_BOT_WIDTH), y);
            this.addChild(sprite,5);
            this.wallLevel1.push(sprite);
        }

        for(var i = 0 ; i < 17 ; i++){
            var sprite = new MyTileNoEvent("res/up_0/34.png");
            sprite.setPosition(x - i*(INFO.TILE.DISTANCE + INFO.TILE.WALL_BOT_WIDTH), y  - 15);
            this.addChild(sprite, 4);
            this.wallLevel2.push(sprite);
        }
    },

    showLeftWall: function(){
        var size = cc.Director.getInstance().getWinSize();
        // Show bot wall
        var widthWall = (INFO.TILE.WALL_BOT_WIDTH + INFO.TILE.DISTANCE)* 17 + INFO.TILE.DISTANCE_OTHER_WALL + INFO.TILE.WALL_LEFT_WIDTH;

        // get start pos of bot wall
        var y = size.height/2 + this.notInArea.height/2 + 3*INFO.TILE.WALL_BOT_HEIGHT - 2*INFO.TILE.OVERPLAY + INFO.TILE.DISTANCE_OTHER_AREA - INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL - INFO.TILE.WALL_LEFT_HEIGHT/2;
        var x = size.width/2 - widthWall/2 + INFO.TILE.WALL_LEFT_WIDTH/2;

        x = parseInt(x, 10);
        y = parseInt(y, 10);

        for(var i = 0 ; i < 17 ; i++){
            var sprite = new MyTileNoEvent("res/up_1/34.png");
            sprite.setPosition(x, y - i*(INFO.TILE.WALL_LEFT_HEIGHT + INFO.TILE.DISTANCE - 15));
            this.addChild(sprite,i + 5);
            this.wallLevel2.push(sprite);
        }

        for(var i = 0 ; i < 17 ; i++){
            var sprite = new MyTileNoEvent("res/up_1/34.png");
            sprite.setPosition(x, y - i*(INFO.TILE.WALL_LEFT_HEIGHT + INFO.TILE.DISTANCE - 15) + 15);
            this.addChild(sprite,i + 6);
            this.wallLevel1.push(sprite);
        }
    },

    showRightWall: function(){
        var size = cc.Director.getInstance().getWinSize();
        // Show bot wall
        var widthWall = (INFO.TILE.WALL_BOT_WIDTH + INFO.TILE.DISTANCE)* 17 + INFO.TILE.DISTANCE_OTHER_WALL + INFO.TILE.WALL_LEFT_WIDTH;

        // get start pos of bot wall
        var y = size.height/2 - this.notInArea.height/2 - 3*INFO.TILE.WALL_BOT_HEIGHT + 2*INFO.TILE.OVERPLAY - INFO.TILE.DISTANCE_OTHER_AREA +  INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL + INFO.TILE.WALL_LEFT_HEIGHT/2;
        var x = size.width/2 + widthWall/2 - INFO.TILE.WALL_LEFT_WIDTH/2;

        x = parseInt(x, 10);
        y = parseInt(y, 10);

        for(var i = 0 ; i < 17 ;i++){
            var sprite = new MyTileNoEvent("res/up_1/34.png");
            sprite.setPosition(x  , y + i*(INFO.TILE.WALL_LEFT_HEIGHT + INFO.TILE.DISTANCE - 15) - 15);
            this.addChild(sprite, 17-i);
            this.wallLevel2.push(sprite);
        }

        for(var i = 0 ; i < 17 ;i++){
            var sprite = new MyTileNoEvent("res/up_1/34.png");
            sprite.setPosition(x  , y + i*(INFO.TILE.WALL_LEFT_HEIGHT + INFO.TILE.DISTANCE - 15) );
            this.addChild(sprite, 34-i);
            this.wallLevel1.push(sprite);
        }
    },

    calculateStartPosition: function () {
        var pos = this.dice % 4;
        if(pos == 0){
            pos = 4;
        }

        var currPos = pos - this.currPlayer.position + 1;
        if(currPos == 0){
            currPos = 4;
        }
        else if(currPos < 0){
            currPos += 4;
        }

        var wallPos = currPos*17 - this.dice;
        var doraPos = wallPos + 3;
        if(doraPos > 4*17){
            doraPos = doraPos - 4*17;
        }
        this.lastDoraPos = doraPos;

        var texture = cc.TextureCache.getInstance().textureForKey("res/up_"+ (currPos -1) +"/" + this.dora + ".png");
        this.wallLevel1[doraPos - 1].setTexture(texture);

        var deadEndPos = wallPos + 7;
        if(deadEndPos > 4*17)
            deadEndPos = deadEndPos - 4*17;

        var tmpLevel1 = [];
        var tmpLevel2 = [];
        for(var i = wallPos ; i < this.wallLevel1.length ; i++){
            tmpLevel1.push(this.wallLevel1[i]);
            tmpLevel2.push(this.wallLevel2[i]);
        }

        for(var i = 0 ; i < wallPos ; i++){
            tmpLevel1.push(this.wallLevel1[i]);
            tmpLevel2.push(this.wallLevel2[i]);
        }

        this.wallLevel1 = tmpLevel1;
        this.wallLevel2 = tmpLevel2;

        // find est pos

    },

    getPlayerPos: function(pos){
        var posCurrentPlay = pos - this.currPlayer.position;
        if(posCurrentPlay < 0){
            posCurrentPlay += 4;//INFO.GAME.NUM_OF_PLAYER;
        }
        posCurrentPlay++;
        return posCurrentPlay;
    },

    initPosition: function(){
        var size = cc.Director.getInstance().getWinSize();

        this.position[1] = {};

        this.position[1].picked = {};
        this.position[1].picked.x = parseInt(size.width/2 -  (INFO.TILE.MAX_TILE_PER_PLAYER*INFO.TILE.BOT_WIDTH + INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL)/2 + INFO.TILE.BOT_WIDTH/2, 10);
        this.position[1].picked.y = parseInt(INFO.TILE.BOT_HEIGHT/2 + 15, 10);

        this.position[3] = {};
        this.position[3].picked = {};
        this.position[3].picked.x = parseInt(size.width/2 +  (INFO.TILE.MAX_TILE_PER_PLAYER*INFO.TILE.TOP_WIDTH + INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL)/2 - INFO.TILE.TOP_WIDTH/2, 10);
        this.position[3].picked.y = parseInt(size.height - INFO.TILE.TOP_HEIGHT/2 - 15, 10);

        this.position[4] = {};
        this.position[4].picked = {};
        this.position[4].picked.x = parseInt(INFO.TILE.LEFT_WIDTH/2 + 15, 10);
        this.position[4].picked.y = parseInt(size.height/2 +  (INFO.TILE.MAX_TILE_PER_PLAYER*INFO.TILE.LEFT_HEIGHT + INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL)/2 + INFO.TILE.LEFT_HEIGHT/2, 10);

        this.position[2] = {};
        this.position[2].picked = {};
        this.position[2].picked.x = parseInt(size.width - INFO.TILE.LEFT_WIDTH/2 - 15, 10);
        this.position[2].picked.y = parseInt(size.height/2 -  (INFO.TILE.MAX_TILE_PER_PLAYER*INFO.TILE.LEFT_HEIGHT + INFO.TILE.DISTANCE_OTHER_DIRECTION_WALL)/2 - INFO.TILE.LEFT_HEIGHT/2, 10);

        // tiles thrown position
        this.position[1].thrown = {};
        this.position[1].thrown.x = parseInt(size.width/2 -  (6*INFO.TILE.WALL_BOT_WIDTH)/2 - INFO.TILE.WALL_BOT_WIDTH/2, 10);
        this.position[1].thrown.y = parseInt(size.height/2 - this.notInArea.height/2 - INFO.TILE.DISTANCE_INFO - INFO.TILE.WALL_BOT_HEIGHT/2, 10);

        this.position[2].thrown = {};
        this.position[2].thrown.x = parseInt(size.width/2 +  this.notInArea.width/2 + INFO.TILE.DISTANCE_INFO + INFO.TILE.THROWN_TILE_WIDTH[2]/2, 10);
        this.position[2].thrown.y = parseInt(size.height/2 - (6*INFO.TILE.THROWN_TILE_HEIGHT[2] - 5*INFO.TILE.OVERPLAY)/2  + INFO.TILE.THROWN_TILE_HEIGHT[2]/2, 10);

        this.position[3].thrown = {};
        this.position[3].thrown.x = parseInt(size.width/2 +  (6*INFO.TILE.WALL_BOT_WIDTH)/2 - INFO.TILE.WALL_BOT_WIDTH/2, 10);
        this.position[3].thrown.y = parseInt(size.height/2 + this.notInArea.height/2 + INFO.TILE.DISTANCE_INFO + INFO.TILE.WALL_BOT_HEIGHT/2, 10);

        this.position[4].thrown = {};
        this.position[4].thrown.x = parseInt(size.width/2 -  this.notInArea.width/2 - INFO.TILE.DISTANCE_INFO - INFO.TILE.THROWN_TILE_WIDTH[4]/2, 10);
        this.position[4].thrown.y = parseInt(size.height/2 + (6*INFO.TILE.THROWN_TILE_HEIGHT[4] - 5*INFO.TILE.OVERPLAY)/2  - INFO.TILE.THROWN_TILE_HEIGHT[4]/2, 10);
    },

    addToBot: function(sprites, tileID){
        var size = cc.Director.getInstance().getWinSize();
        var x = this.position[1].picked.x;
        var y = this.position[1].picked.y;

        if(this.isPick){
            x+= INFO.TILE.DISTANCE_TILE_PICK;
        }

        for(var i = 0 ; i < sprites.length ; i++){
            var sprite;
            if(tileID != undefined){
                sprite = new MyTile("res/front/"+ tileID  +".png");
                sprite.ID = tileID;
            }
            else{
                sprite = new MyTile("res/front/"+ this.currPlayer.leftTiles[this.botTiles.length]  +".png");
            }

            sprite.setPosition(sprites[i].getPosition().x, sprites[i].getPosition().y);
            this.removeChild(sprites[i]);
            this.addChildHasEvent(sprite, INFO.TILE.ORDER_PICKED);
            var move = cc.MoveBy.create(0.3, cc.p(x + this.botTiles.length*(INFO.TILE.BOT_WIDTH) - sprites[i].getPosition().x, y - sprites[i].getPosition().y ));
            sprite.runAction(cc.Sequence.create(move));
            this.botTiles.push(sprite);
            sprite.enableEvent = tileID != undefined;

            sprite.onTap = function(){
                var parent = this._parent;
                parent.callThrowTile(this.ID);
            }
        }
    },

    addToLeft: function(sprites){
        var x = this.position[4].picked.x;
        var y = this.position[4].picked.y;

        if(this.isPick){
            y -= INFO.TILE.DISTANCE_TILE_PICK;
        }

        for(var i = 0 ; i < sprites.length ; i++){
            var sprite = new MyTileNoEvent("res/left/34.png");
            sprite.setPosition(sprites[i].getPosition().x, sprites[i].getPosition().y);
            this.removeChild(sprites[i]);
            this.addChild(sprite, INFO.TILE.ORDER_PICKED);
            var move = cc.MoveBy.create(0.3, cc.p(x - sprites[i].getPosition().x, y - this.leftTiles.length*(INFO.TILE.LEFT_HEIGHT) - sprites[i].getPosition().y ));

            sprite.runAction(cc.Sequence.create(move));
            this.leftTiles.push(sprite);
        }
    },

    addToRight: function(sprites){
        var x = this.position[2].picked.x;
        var y = this.position[2].picked.y;

        if(this.isPick){
            y += INFO.TILE.DISTANCE_TILE_PICK;
        }

        for(var i = 0 ; i < sprites.length ; i++){
            var sprite = new MyTileNoEvent("res/right/34.png");
            sprite.setPosition(sprites[i].getPosition().x, sprites[i].getPosition().y);
            this.removeChild(sprites[i]);
            this.addChild(sprite, INFO.TILE.ORDER_PICKED - this.rightTiles.length);
            var move = cc.MoveBy.create(0.3, cc.p(x - sprites[i].getPosition().x, y + this.rightTiles.length*(INFO.TILE.LEFT_HEIGHT) - sprites[i].getPosition().y ));

            sprite.runAction(cc.Sequence.create(move));
            this.rightTiles.push(sprite);
        }
    },

    addToTop: function(sprites){
        var x = this.position[3].picked.x;
        var y = this.position[3].picked.y;

        if(this.isPick){
            x -= INFO.TILE.DISTANCE_TILE_PICK;
        }

        for(var i = 0 ; i < sprites.length ; i++){
            var sprite = new MyTileNoEvent("res/back/34.png");
            sprite.setPosition(sprites[i].getPosition().x, sprites[i].getPosition().y);
            this.removeChild(sprites[i]);
            this.addChild(sprite, INFO.TILE.ORDER_PICKED);
            var move = cc.MoveBy.create(0.3, cc.p(x - this.topTiles.length*(INFO.TILE.TOP_WIDTH) - sprites[i].getPosition().x, y - sprites[i].getPosition().y ));

            sprite.runAction(cc.Sequence.create(move));
            this.topTiles.push(sprite);
        }
    },

    addToThrownArea: function(sprite, pos, tileID, callback){
        if(tileID == undefined){
            tileID = sprite.ID;
        }

        console.log("Add to thrown tiles area: tileID = " + sprite.ID);

        var x = this.position[pos].thrown.x;
        var y = this.position[pos].thrown.y;
        var length = this.tilesThrown[pos].length % INFO.TILE.NUM_OF_ROW_THROWN_TILE;
        var level = parseInt(this.tilesThrown[pos].length / INFO.TILE.NUM_OF_ROW_THROWN_TILE, 10);

        if(level > 2){
            level = 2;
            length += INFO.TILE.NUM_OF_ROW_THROWN_TILE;
        }

        var order = INFO.TILE.ORDER_THROWN_TILE[pos];

        if(pos == 1 || pos == 3){
            x += (2 - pos)*length*(INFO.TILE.THROWN_TILE_WIDTH[pos]);
            y += (pos - 2)*level*(INFO.TILE.THROWN_TILE_HEIGHT[pos] - INFO.TILE.OVERPLAY);

            x += (2 - pos)*INFO.TILE.DISTANCE_WITH_NEW_THROWN_TILE;
            y += (pos - 2)*INFO.TILE.DISTANCE_WITH_NEW_THROWN_TILE;
        }
        else {
            x += (3 - pos)*level*INFO.TILE.THROWN_TILE_WIDTH[pos];
            y += (3 - pos)*length*(INFO.TILE.THROWN_TILE_HEIGHT[pos] - INFO.TILE.OVERPLAY);

            x += (3 - pos)*INFO.TILE.DISTANCE_WITH_NEW_THROWN_TILE;
            y += (3 - pos)*INFO.TILE.DISTANCE_WITH_NEW_THROWN_TILE;
        }

        var newSprite = new MyTileNoEvent("res/up_"+ (pos - 1) +"/" + tileID +".png");
        newSprite.setPosition(sprite.getPosition().x, sprite.getPosition().y);
        newSprite.ID = tileID;
        this.removeChildHasEvent(sprite);
        var tmpOrder = INFO.TILE.ORDER_ANIMATION;

        if(pos == 2){
            tmpOrder += this.tilesThrown[pos].length;
        }

        this.addChild(newSprite, tmpOrder);

        var move = cc.MoveTo.create(INFO.TILE.TIME_THROWN_TILE, cc.p(x, y));
        var action = cc.Sequence.create(move);
        action.onFinished = function(target){
            target.getParent().reorderChild(target, INFO.TILE.ORDER_ANIMATION - target.getZOrder() + order);
            if(callback != undefined){
                callback(target);
            }
        };
        this.tilesThrown[pos].push(newSprite);
        newSprite.runAction(action);

    },


    sortContainerAfterAddNewSprite: function(container){
        for(var i = 0 ; i < container.length ; i++){
            if(i < container.length - 1){
                if(container[i].ID > container[container.length - 1].ID){
                    var sprite = container.pop();
                    container.splice(i, 0, sprite);
                    break;
                }
                else if(container[i].ID == container[container.length - 1].ID && container[i + 1].ID != container[container.length - 1].ID){
                    var sprite = container.pop();
                    container.splice(i + 1, 0, sprite);
                    break;
                }

            }
        }
    },

    correctPosition: function(container, pos){
        this.sortContainerAfterAddNewSprite(container);
        if(container.length > 1){
            var x = this.position[pos].picked.x;
            var y = this.position[pos].picked.y;

            var width = container[0].getBoundingBox().getWidth();
            var height = container[0].getBoundingBox().getHeight();

            var flag = (pos == 1 || pos == 3) ;

            for(var i = 0 ; i < container.length ; i++){
                var tmpPos = {};
                tmpPos.x = x;
                tmpPos.y = y;
                if(flag){
                    if(pos == 1){
                        tmpPos.x +=  i * width;
                        tmpPos.y = container[i].getPosition().y;
                    }
                    else{
                        tmpPos.x -=  i * width;
                    }
                }
                else{
                    if(pos == 2){
                        tmpPos.y +=  i *(height - INFO.TILE.OVERPLAY_LEFT_RIGHT + INFO.TILE.DISTANCE);
                    }
                    else{
                        tmpPos.y -=  i *(height - INFO.TILE.OVERPLAY_LEFT_RIGHT + INFO.TILE.DISTANCE);
                    }
                }
                var move = cc.MoveTo.create(INFO.TILE.TIME_SORT_THROWN_TILE, cc.p(tmpPos.x, tmpPos.y));
                var action = cc.Sequence.create(move);
                action.onFinished = function(target){
                    target.enableEvent = true;
                };
                container[i].enableEvent = false;

                container[i].runAction(action);
            }
        }
    },

    correctTilesThrownPosition: function(pos){

        var length = 0;
        var level = 0;

        for(var i = 0 ; i < this.tilesThrown[pos].length; i++){

            var x = this.position[pos].thrown.x;
            var y = this.position[pos].thrown.y;

            length = (i) % INFO.TILE.NUM_OF_ROW_THROWN_TILE;
            level = parseInt((i) / INFO.TILE.NUM_OF_ROW_THROWN_TILE, 10);

            if(level > 2){
                level = 2;
                length +=  INFO.TILE.NUM_OF_ROW_THROWN_TILE;
            }

            if(pos == 1 || pos == 3){
                x += (2 - pos)*length*(INFO.TILE.THROWN_TILE_WIDTH[pos]);
                y += (pos - 2)*level*(INFO.TILE.THROWN_TILE_HEIGHT[pos] - INFO.TILE.OVERPLAY);
            }
            else {
                x += (3 - pos)*level*INFO.TILE.THROWN_TILE_WIDTH[pos];
                y += (3 - pos)*length*(INFO.TILE.THROWN_TILE_HEIGHT[pos] - INFO.TILE.OVERPLAY);
            }

            var move = cc.MoveTo.create(INFO.TILE.TIME_SORT_THROWN_TILE, cc.p(x, y));
            var action = cc.Sequence.create(move);
            this.tilesThrown[pos][i].runAction(action);
        }

    },

    sortTilesAnimation: function () {
        // bot
        for(var i = 0 ; i < this.botTiles.length ; i++){
            var texture = cc.TextureCache.getInstance().textureForKey("res/up_0/35.png");
            this.botTiles[i].setTexture(texture);
            this.botTiles[i].enableEvent = true;
        }
        var that = this;
        setTimeout(function(){
            for(var i = 0 ; i < that.botTiles.length ; i++){
                var texture = cc.TextureCache.getInstance().textureForKey("res/front/"+ that.currPlayer.leftTilesOrderd[i] +".png");
                that.botTiles[i].setTexture(texture);
                that.botTiles[i].ID = that.currPlayer.leftTilesOrderd[i];
            }
        }, 500);

        // right
        var tmpRightArr = [];
        for(var i = 0 ; i < this.rightTiles.length ; i++){
            this.removeChild(this.rightTiles[i]);
            var sprite = cc.Sprite.create("res/up_1/35.png");
            sprite.setPosition(this.rightTiles[i].getPosition().x - 20, this.rightTiles[i].getPosition().y);
            tmpRightArr.push(sprite);
            this.addChild(sprite, this.rightTiles.length - i);
        }
        that = this;
        setTimeout(function(){
            for(var i = 0 ; i < that.rightTiles.length ; i++){
                var tmp = tmpRightArr.pop();
                that.removeChild(tmp);
                delete  tmp;
                that.addChild(that.rightTiles[i]);
            }
        }, 500);

        //top

        for(var i = 0 ; i < this.topTiles.length ; i++){
            var texture = cc.TextureCache.getInstance().textureForKey("res/up_2/35.png");
            this.topTiles[i].setTexture(texture);
        }
        that = this;
        setTimeout(function(){
            for(var i = 0 ; i < that.topTiles.length ; i++){
                var texture = cc.TextureCache.getInstance().textureForKey("res/back/34.png");
                that.topTiles[i].setTexture(texture);
            }
        }, 500);

        //left
        var tmpLeftArr = [];
        for(var i = 0 ; i < this.leftTiles.length ; i++){
            this.removeChild(this.leftTiles[i]);
            var sprite = cc.Sprite.create("res/up_3/35.png");
            sprite.setPosition(this.leftTiles[i].getPosition().x + 20, this.leftTiles[i].getPosition().y);
            tmpLeftArr.push(sprite);
            this.addChild(sprite);
        }
        var that = this;
        setTimeout(function(){
            for(var i = 0 ; i < that.leftTiles.length ; i++){
                var tmp = tmpLeftArr.pop();
                that.removeChild(tmp);
                delete  tmp;
                that.addChild(that.leftTiles[i]);
            }
        }, 500);

        if(this.currPlayer.position == 1){
            setTimeout(function(){
                that.loopGame();
            }, 600);
        }
    },

    setDiscardTilePos: function(pos, container, sprite, isLate){
        var size = cc.Director.getInstance().getWinSize();
        var halfWidth = parseInt(sprite.getBoundingBox().getWidth()/2, 10);
        var halfHeight = parseInt(sprite.getBoundingBox().getHeight()/2, 10);

        if(isLate){
            for(var i = 0 ; i < container.length ; i++){
                if(sprite.ID == container[i].ID && container[i].getBoundingBox().getHeight() < container[i].getBoundingBox().getWidth()){
                    switch (pos){
                        case 1:
                            sprite.pos.x = container[i].pos.x;
                            sprite.pos.y = container[i].pos.y + container.getBoundingBox().getHeight();
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                    }

                    container.splice(i, 0 , sprite);
                    count++;
                }
            }
        }

        switch (pos){
            case 1:
                if(container.length == 0){
                    sprite.pos.x = size.width - halfWidth - 5;
                    sprite.pos.y = halfHeight + 15;
                }
                else{
                    var lastSprite =  container[container.length - 1];
                    sprite.pos.x = lastSprite.pos.x - lastSprite.getBoundingBox().getWidth()/2 - halfWidth;
                    sprite.pos.y = halfHeight + 15;
                }
                break;
            case 2:
                if(container.length == 0){
                    sprite.pos.x = size.width - halfWidth - 15;
                    sprite.pos.y = size.height - halfHeight - 5;
                }
                else{
                    var lastSprite =  container[container.length - 1];
                    sprite.pos.x = size.width - halfWidth - 15;
                    sprite.pos.y = lastSprite.pos.y - lastSprite.getBoundingBox().getHeight()/2 - (halfHeight - INFO.TILE.OVERPLAY);
                }
                break;
            case 3:
                if(container.length == 0){
                    sprite.pos.x = halfWidth + 5;
                    sprite.pos.y = size.height - halfHeight - 15;
                }
                else{
                    var lastSprite =  container[container.length - 1];
                    sprite.pos.x = lastSprite.pos.x + lastSprite.getBoundingBox().getWidth()/2 + halfWidth;
                    sprite.pos.y = size.height - halfHeight - 15;
                }
                break;
            case 4:
                if(container.length == 0){
                    sprite.pos.x = halfWidth + 15;
                    sprite.pos.y = halfHeight + 5;
                }
                else{
                    var lastSprite =  container[container.length - 1];
                    sprite.pos.x = halfWidth + 15;
                    sprite.pos.y = lastSprite.pos.y + lastSprite.getBoundingBox().getHeight()/2 + (halfHeight - INFO.TILE.OVERPLAY);
                }
                break;
        }
        container.push(sprite);
    },

    getNewPositionDiscardTile: function(pos, container, newSprite){
        var size = cc.Director.getInstance().getWinSize();
        var p = {x: 0, y :0};
        switch (pos){
            case 1:
                if(container.length == 0){
                    p.x = size.width - newSprite.getBoundingBox().getWidth()/2 - 5;
                    p.y = newSprite.getBoundingBox().getHeight()/2 + 15;
                }
                else{
                    var sprite =  container[container.length - 1];
                    p.x = sprite.nextPos.x - sprite.getBoundingBox().getWidth()/2 - newSprite.getBoundingBox().getWidth()/2;
                    p.y = newSprite.getBoundingBox().getHeight()/2 + 15;
                }
                break;
            case 2:
                if(container.length == 0){
                    p.x = size.width - newSprite.getBoundingBox().getWidth()/2 - 15;
                    p.y = size.height - newSprite.getBoundingBox().getHeight()/2 - 5;
                }
                else{
                    var sprite =  container[container.length - 1];
                    p.x = size.width - newSprite.getBoundingBox().getWidth()/2 - 15;
                    p.y = sprite.nextPos.y - sprite.getBoundingBox().getHeight()/2 - (newSprite.getBoundingBox().getHeight()/2 - INFO.TILE.OVERPLAY);
                }
                break;
            case 3:
                if(container.length == 0){
                    p.x = newSprite.getBoundingBox().getWidth()/2 + 5;
                    p.y = size.height - newSprite.getBoundingBox().getHeight()/2 - 15;
                }
                else{
                    var sprite =  container[container.length - 1];
                    p.x = sprite.nextPos.x + sprite.getBoundingBox().getWidth()/2 + newSprite.getBoundingBox().getWidth()/2;
                    p.y = size.height - newSprite.getBoundingBox().getHeight()/2 - 15;
                }
                break;
            case 4:
                if(container.length == 0){
                    p.x = newSprite.getBoundingBox().getWidth()/2 + 15;
                    p.y = newSprite.getBoundingBox().getHeight()/2 + 5;
                }
                else{
                    var sprite =  container[container.length - 1];
                    p.x = newSprite.getBoundingBox().getWidth()/2 + 15;
                    p.y = sprite.nextPos.y + sprite.getBoundingBox().getHeight()/2 + (newSprite.getBoundingBox().getHeight()/2 - INFO.TILE.OVERPLAY);
                }
                break;
        }

        p.x = parseInt(p.x, 10);
        p.y = parseInt(p.y, 10);

        if(container.length == 0) {
            newSprite.nextPos.x = p.x;
            newSprite.nextPos.y = p.y;
        }
        else{
            var sprite =  container[container.length - 1];
            sprite.nextPos.x = p.x;
            sprite.nextPos.y = p.y;
        }
        return p;
    },

    addToDiscardTileContainer: function(container, ownerPos ,  pos, sprite, isLate){
        if(sprite.ID == undefined){
            sprite.ID = 0;
        }
        var newSprite = new MyTileNoEvent("res/up_" + (pos - 1) + "/" + sprite.ID + ".png");
        newSprite.setPosition(sprite.getPosition().x, sprite.getPosition().y);
        newSprite.ID = sprite.ID;
        this.removeChild(sprite);
        if(ownerPos == 4){
            this.addChild(newSprite, 20 - container.length);
        }
        else{
            this.addChild(newSprite);
        }

        this.setDiscardTilePos(ownerPos, container, newSprite, isLate);
        console.log("pos : " + newSprite.pos.x  + "," + newSprite.pos.y);
        var move = cc.MoveTo.create(INFO.TILE.TIME_THROWN_TILE, cc.p(newSprite.pos.x, newSprite.pos.y));
        newSprite.runAction(cc.Sequence.create(move));

    },

    addToDiscardArea: function(container, ownerPos, pos ,ownerSprites, otherSprite, type){
        var tmpPos = pos - ownerPos;
        if(tmpPos < 0){
            tmpPos += INFO.GAME.MAX_PLAYER;
        }
        switch (type){
            case INFO.TYPE_WIN_TILE.CHI:
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                break;
            case INFO.TYPE_WIN_TILE.PON:
                switch (tmpPos){
                    case 1:
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        break;
                    case 2:
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        break;
                    case 3:
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        break;
                }

                break;
            case INFO.TYPE_WIN_TILE.OPENKAN:
                switch (tmpPos){
                    case 1:
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[2]);
                        break;
                    case 2:
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[2]);
                        break;
                    case 3:
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                        this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[2]);
                        this.addToDiscardTileContainer(container,ownerPos, pos, otherSprite);
                        break;
                }
                break;
            case INFO.TYPE_WIN_TILE.CLOSEKAN:
                ownerSprites[0].ID = 35;
                ownerSprites[3].ID = 35;
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0]);
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[1]);
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[2]);
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[3]);
                break;
            case INFO.TYPE_WIN_TILE.LATEKAN:
                this.addToDiscardTileContainer(container, ownerPos,ownerPos, ownerSprites[0], true);
                break;
        }


        var that = this;
        that.correctPosition(that.tilesPicked[ownerPos], ownerPos);
        setTimeout(function(){
            that.hideSkipButton();
        },400);
    },

    showAlert: function(text){
        var size = cc.Director.getInstance().getWinSize();
        var label = cc.LabelTTF.create(text, INFO.MESSAGEBOX.FONT, 50);
        label.setPosition(size.width/2, 15 + INFO.TILE.BOT_HEIGHT + label.getBoundingBox().getHeight()/2 + 10);

        this.addChild(label, 100);

        label.setScale(0.5);

        var myScale = cc.ScaleTo.create(0.4, 1, 1);

        label.runAction(cc.Sequence.create(myScale));
        var that = this;
        setTimeout(function(){
            that.removeChild(label);
        }, 500);

    },

    showSkipButton: function(){

        var size = cc.Director.getInstance().getWinSize();
        this.skipButton.setPosition(size.width - this.skipButton.getBoundingBox().getWidth()/2 - 30, INFO.TILE.BOT_HEIGHT  + 5 + this.skipButton.getBoundingBox().getHeight()/2);
        this.addChildHasEvent(this.skipButton, 200);

    },

    hideSkipButton: function(){
        this.removeChildHasEvent(this.skipButton);
    },

    callThrowTile: function(tileID){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("call throw tile: " + tileID);
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("throwTile", {tile: tileID}, conn.sfs.lastJoinedRoom));
        }
    },

    callPickTile: function(){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call pick tile");
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("pickTile", null, conn.sfs.lastJoinedRoom));
        }
    },

    callCHI: function(tiles){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call Chi: " + tiles[0] + ", " + tiles[1]);
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callChi", {chiTiles: tiles}, conn.sfs.lastJoinedRoom));
        }
    },

    callPON: function(tile){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call Pon: " + tile);
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callPon", {tile: tile}, conn.sfs.lastJoinedRoom));
        }
    },

    callKAN: function(tile, type){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call Kan: " + tile);
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callKan", {tile: tile, kanType: type}, conn.sfs.lastJoinedRoom));
        }
    },

    callPickTileFromDeathWall: function(){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call pick tile from death wall");
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("pickTileFromDeathWall", null, conn.sfs.lastJoinedRoom));
        }
    },

    callCancelKan: function(){
        if(this.canDoTile){
            this.canDoTile = false;
            console.log("Call cancel KAN");
            conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("cancelKan", null, conn.sfs.lastJoinedRoom));
        }
    },

    callTSUMO: function(){
        console.log("Call TSUMO");
        conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callTsumo", null, conn.sfs.lastJoinedRoom));
    },

    callRON: function(){
        console.log("Call RON");
        conn.sfs.send( new SFS2X.Requests.System.ExtensionRequest("callRon", null, conn.sfs.lastJoinedRoom));
    },

    setEventResponse: function(callback){
        console.log("set listener");
        conn.sfs.removeEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, callback, this);
        conn.sfs.addEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, callback, this);
    },

    showTiles: function(pos, tileIDs, callback){
        var tmp = "";
        if(pos == 1){
            tmp = "up_front";
        }
        else{
            tmp = "up_" + (pos - 1);
        }
        for(var i = 0; i < this.tilesPicked[pos].length; i++){
            this.tilesPicked[i].setImage("res/" + tmp + "/" + tileIDs[i] + ".png");
        }
        if(callback){
            callback(this);
        }
    }

});